<?php
class UPagseguro
{
	public $email;
	public $type = 'CP';
	public $currency = 'BRL';
	public $shipping = 'EN';
	public $encoding = 'UTF-8';
	public $url = 'https://pagseguro.uol.com.br/checkout/checkout.jhtml';
	public $verifyUrl = 'https://pagseguro.uol.com.br/pagseguro-ws/checkout/NPI.jhtml';
	public $fields = array();
	public $data = array();
	public $token;
	
	public function __construct($options)
	{
		foreach($options as $k=>$v)
			$this->$k = $v;
		$this->addField('email_cobranca',$this->email);
		$this->addField('tipo',$this->type);
		$this->addField('moeda',$this->currency);
		$this->addField('tipo_frete',$this->shipping);
		$this->addField('encoding',$this->encoding);
	}
	
	public function addField($key,$value)
	{
		$this->fields[$key] = $value;
	}
	
	public function getForm()
	{
		$html = CHtml::beginForm($this->url,'post',array('id'=>'payseguroForm'));
		foreach ($this->fields as $name => $value)
			$html.= CHtml::hiddenField($name,$value);
		$html.= CHtml::endForm();
		$html.= CHtml::script('jQuery("#payseguroForm").submit();');
		
		return $html;
	}
	
	public function verify()
	{
		$data = 'Comando=validar&Token='.$this->token;
		foreach($_POST as $k=>$v)
		{
			$this->data[$k] = $v;
			$v = get_magic_quotes_gpc()?$v:addslashes($v);
			$data.= "&$k=$v";
		}
		
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $this->verifyUrl);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$content = trim(curl_exec($curl));
		curl_close($curl);
		
		/*
		$result = '';
		$fp = fsockopen("ssl://pagseguro.uol.com.br", 443, $errno, $errstr, 30);
		if (!$fp) {
		    echo "$errstr ($errno)<br />\n";
		} else {
		    $out = "POST /pagseguro-ws/checkout/NPI.jhtml HTTP/1.1\r\n";
		    $out .= "Host: pagseguro.uol.com.br\r\n";
		    $out .= "Content-type: application/x-www-form-urlencoded\r\n"; 
			$out .= "Content-length: " . strlen($data) . "\r\n"; 
		    $out .= "Connection: Close\r\n\r\n";
		    fwrite($fp, $out);
		    fwrite($fp, $data); 
		    while (!feof($fp)) {
		        $result.= fgets($fp, 128);
		    }
		    fclose($fp);
		}
		$result = preg_replace('/\r/','',$result);
		list($headers,$content) = explode("\n\n",$result);
		*/
		
		return $content == "VERIFICADO";
	}
	
	public function formatAmount($amount)
	{
		$amount = str_replace(',','.',$amount);
		$parts = explode('.',$amount);
		if(!isset($parts[1]))
			$parts[1] = '00';
		if(strlen($parts[1]) < 2)
			$parts[1].= '0';
		return implode('',$parts);
	}
}